package com.lc.user.express.ordering;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.lc.user.express.BaseSecondActivity;
import com.lc.user.express.R;
import com.lc.user.express.adapter.AddrAdapter;
import com.lc.user.express.app.AppContext;
import com.lc.user.express.httpserver.GetAddrAdd;
import com.lc.user.express.httpserver.GetAddrInfo;
import com.lc.user.express.httpserver.GetAddrUpdate;
import com.lc.user.express.model.AddrModel;
import com.lc.user.express.utils.GetToast;
import com.lc.user.express.view.dialog.AffirmDialog;
import com.zcx.helper.http.AsyCallBack;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/3/7.新增常用路线 修改常用路线
 */
public class AddUsedRouteActivity extends BaseSecondActivity {
    public static final int TYPE_ADD = 0x11;//新增常用路线
    public static final int TYPE_EDIT = 0x12;//修改常用路线
    public static OnAddrChange onAddrChange = null;//监听地址

    private TextView tv_add_end_addr;//添加目的地

    private ListView lv;//地址列表
    private List<AddrModel> list = new ArrayList<>();
    private AddrAdapter adapter;

    private EditText et_route_name;//线路名称
    private int tposition = -1;//记录点选地址位置

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_used_route);
        setTitle(getIntent().getFlags() == TYPE_ADD ? "新增常用路线" : "修改常用路线");
        initView();
        initData();
    }

    private void initView() {
        ((TextView)findViewById(R.id.tv_public)).setOnClickListener(this);
        et_route_name = (EditText)findViewById(R.id.et_route_name);

        View view = LayoutInflater.from(cnt).inflate(R.layout.rooter_add_used_route,null);
        AppContext.ScaleScreenHelper.loadView((ViewGroup)view);
        tv_add_end_addr = (TextView) view.findViewById(R.id.tv_add_end_addr);
        tv_add_end_addr.setOnClickListener(this);

        lv = (ListView) findViewById(R.id.lv);
        lv.addFooterView(view,null,false);
        adapter = new AddrAdapter(cnt, list,true);
        lv.setAdapter(adapter);
        lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

                deleteAddr(position);

                return true;
            }
        });
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                tposition = position;
                Bundle bundle = new Bundle();
                bundle.putSerializable("addr", list.get(position));
                if (position == 0) {
                    show(SearchAddrActivity.class, SearchAddrActivity.TYPE_S, bundle);
                } else {
                    show(SearchAddrActivity.class, SearchAddrActivity.TYPE_E, bundle);
                }
            }
        });
        onAddrChange = new OnAddrChange() {
            @Override
            public void onAddr(AddrModel model) {
                if(tposition != -1){
                    list.get(tposition).setAddr(model.getAddr());
                    list.get(tposition).setDistrict(model.getDistrict());
                    list.get(tposition).setLat(model.getLat());
                    list.get(tposition).setLng(model.getLng());
                    list.get(tposition).setName(model.getName());
                    list.get(tposition).setMobile(model.getMobile());
                    list.get(tposition).setPoint(model.getPoint());
                    adapter.updateListView(list);
                }

            }
        };
    }

    private void initData(){
        if(getIntent().getFlags() == TYPE_EDIT){
            getAddrData();
            et_route_name.setText(getIntent().getStringExtra("routename"));
            et_route_name.setSelection(et_route_name.getText().toString().length());
        }else {
            AddrModel model = new AddrModel();
            model.setAddr("");
            list.add(model);
            AddrModel model1 = new AddrModel();
            model.setAddr("");
            list.add(model1);
        }
        adapter.updateListView(list);
    }
    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_add_end_addr:
                AddrModel model = new AddrModel();
                model.setAddr("");
                list.add(model);
                adapter.updateListView(list);
                break;
            case R.id.tv_public:
                if(ifcommit()){

                    if(getIntent().getFlags() == TYPE_ADD){
                        addCommit();
                    }else if(getIntent().getFlags() == TYPE_EDIT){
                        updateCommit();
                    }
                }
                break;
        }
    }

    /**
     * @param position
     * 地址删除
     */
    private void deleteAddr(final int position) {
        if (position == 0 || list.size() <= 2) {
            return;
        }
        new AffirmDialog(cnt, "确定删除该目的地吗？", "取消", "确定", R.style.MyDialog) {

            @Override
            protected void onYesClick() {

                // TODO Auto-generated method stub
                list.remove(position);
                adapter.updateListView(list);

            }
        }.show();
    }

    /**
     * @return 是否可提交
     */
    private boolean ifcommit(){
        if(TextUtils.isEmpty(et_route_name.getText().toString().trim())){
            GetToast.useString(cnt,"请输入路线名称,方便记忆");
            return false;
        }
        for(int i=0;i<list.size();i++){
            if(TextUtils.isEmpty(list.get(i).getAddr())){
                GetToast.useString(cnt,"请完善路线信息");
                return false;
            }
        }
        return true;
    }

    private void addCommit(){
        new GetAddrAdd(AppContext.myPreferences.getUid(),et_route_name.getText().toString().trim(), GetAddrAdd.addrListTojson(list),new AsyCallBack<Object>() {
            @Override
            public void onSuccess(String toast, int type, Object o) throws Exception {
                if("1".equals(o)){
                    if(SelectUsedRouteActivity.onRefreshView != null){
                        SelectUsedRouteActivity.onRefreshView.onRefresh();
                    }
                    if(ManageUsedRouteActivity.onRefreshView != null){
                        ManageUsedRouteActivity.onRefreshView.onRefresh();
                    }
                    finish();
                }
            }
            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);
                GetToast.useString(cnt,toast);
            }
        }).execute(cnt);
    }
    private void updateCommit(){
        new GetAddrUpdate(AppContext.myPreferences.getUid(),getIntent().getStringExtra("routeId"),et_route_name.getText().toString().trim(), GetAddrAdd.addrListTojson(list),new AsyCallBack<Object>() {
            @Override
            public void onSuccess(String toast, int type, Object o) throws Exception {
                if("1".equals(o)){
                    if(ManageUsedRouteActivity.onRefreshView != null){
                        ManageUsedRouteActivity.onRefreshView.onRefresh();
                    }
                    if(SelectUsedRouteActivity.onRefreshView != null){
                        SelectUsedRouteActivity.onRefreshView.onRefresh();
                    }
                    finish();
                }
            }
            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);
                GetToast.useString(cnt,toast);
            }
        }).execute(cnt);
    }
    private void getAddrData(){
        new GetAddrInfo(AppContext.myPreferences.getUid(),getIntent().getStringExtra("routeId"),new AsyCallBack<GetAddrInfo.Info>() {
            @Override
            public void onSuccess(String toast, int type, GetAddrInfo.Info info) throws Exception {
                list.addAll(info.dataList);
                adapter.updateListView(list);
            }
        }).execute(cnt);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        onAddrChange = null;
    }

    public interface OnAddrChange{
        void onAddr(AddrModel model);
    }
}
